package com.cactus.utils;

import com.alibaba.fastjson2.JSON;
import com.cactus.config.JwtConfigure;
import com.cactus.entity.JeeUserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: cactus
 * @CreateDate: 2023/9/14 11:49
 * @Description: jwt工具
 */
@Component
public class JwtTokenUtil {

    private static final long serialVersionUID = -5625635588908941275L;

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";


    public UserDetails getUsernameFromToken(String token) {
        JeeUserDetails user;
        try {
            Claims claims = getClaimsFromToken(token);
            String subject = claims.getSubject();
            user = JSON.parseObject(subject, JeeUserDetails.class);
        } catch (Exception e) {
            user = null;
        }
        return user;
    }


    public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }


    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(JwtConfigure.SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + JwtConfigure.EXPIRATION_TIME * 1000);
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }

    public String generateToken(UserDetails userDetails) {
        //JeeUserDetails user = (JeeUserDetails) userDetails;
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, JSON.toJSONString(userDetails));
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }



    String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, JwtConfigure.SECRET)
                .compact();
    }

    public Boolean canTokenBeRefreshed(String token) {
        return !isTokenExpired(token);
    }

    public String refreshToken(String token) {
        String refreshedToken;
        try {
            final Claims claims = getClaimsFromToken(token);
            claims.put(CLAIM_KEY_CREATED, new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        JeeUserDetails user = (JeeUserDetails) userDetails;
        UserDetails usernameFromToken = getUsernameFromToken(token);
        String username = usernameFromToken.getUsername();
        return (
                username.equals(user.getUsername())
                        && !isTokenExpired(token)
        );
    }

}
